<template>
  <div class="content">
    <div class="main">

      <form>
        <van-search
          v-model="value"
          :placeholder="defaultKeyword?.keyword"
          :clearable="true"
          :show-action="true"
          @focus="debounced"
          @input="debounced"
          @keydown.enter="gotoSearchDetails"
          @cancel="cancelHandel"
          @blur="loseFocus"
          ref="inputRef"
        />
      </form>

      <!--  历史数据    -->
      <div class="historySearch" v-show="!searchData.length && historyList.length">
        <div class="header">
          <div class="title">历史搜索</div>
          <i @click="clearHistory">
            <van-icon name="delete-o"/>
          </i>
        </div>
        <div class="item">
          <span class="historyItem" v-for="(item,index) in historyList" :key="index"
                @click="historyHandel(item,index)">{{ item }}</span>
        </div>
      </div>

      <div v-show="!searchData.length">
        <div class="title">
          <h3 class="search">热门搜索</h3>
        </div>
        <div class="choose">
        <span v-for="(hotKeyword,index) in hotKeywordVOList" @click="historyItemHandel(hotKeyword.keyword)"
              :class="{chooseItem:true,active:index === 0}"
              :key="hotKeyword.extra?.resourcesId">{{ hotKeyword.keyword }}</span>
        </div>
      </div>

      <div class="listData" v-show="searchData.length">
        <div class="item" v-for="(item,index) in searchData" :key="index" @click="selectItem(item)">
          <span class="goods">{{ item }}</span>
          <i>
            <van-icon name="arrow"/>
          </i>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Search",
});
</script>

<script lang="ts" setup>
import { ref, watch, onMounted, computed, nextTick } from 'vue';
import useSearchStore from '@/stores/modules/search'
import { storeToRefs } from 'pinia'
import { getKeywordApi } from '@/api/search'
import { useRouter, useRoute } from 'vue-router'
import { debounce } from 'lodash'


const props = defineProps({
  isShow: Boolean,
  valueDta: String
})

onMounted(() => {
  const data = JSON.parse(localStorage.getItem('historyList') as string) || []
  const resetHistoryList = new Set(data) as any
  historyList.value = [...resetHistoryList]
  nextTick(() => {
    inputRef.value.focus()
  })
})

const Router = useRouter()
const route = useRoute()
const searchStore = useSearchStore()
const {defaultKeyword, hotKeywordVOList, errorIsShow} = storeToRefs(searchStore)
searchStore.getPopular()
// 搜索框数据
const value = ref<string>('');
// 搜索数据
const searchData = ref<string[]>([])


// 防抖
const debounced = debounce(fuzzySearch, 100, {leading: true, trailing: true})

// 获取搜索值
async function fuzzySearch(e: Event) {
  value.value = (e.target as HTMLInputElement).value
  searchData.value = await getKeywordApi(value.value)
}


// 历史数据
const historyList = ref<string[]>([])
// 选择的数据
const searchValue = ref<string>('')
// 保存搜索数据
const searchItem = ref('')
const selectItem = (item: string) => {
  searchItem.value = item
  historyList.value?.push(item)
  const data = new Set(historyList.value)
  historyList.value = [...data]
  localStorage.setItem('historyList', JSON.stringify([...data]))
  searchValue.value = item
  searchData.value = []
  emits('update:isShow', false)
  value.value = ''
  Router.push(
    {
      path: '/searchDetails',
      query: {
        keyword: item,
      },
    },
  )
}
// 回车搜索
const gotoSearchDetails = () => {
  if (value.value === '') {
    emits('update:isShow', false)
    historyList.value?.push(defaultKeyword.value.keyword)
    const data = new Set(historyList.value)
    localStorage.setItem('historyList', JSON.stringify([...data]))
    historyList.value = [...data]
    searchData.value = []
    Router.push(
      {
        path: '/searchDetails',
        query: {keyword: defaultKeyword.value.keyword},
      },
    )

  } else if (value.value !== '' && searchData.value.length < 1) {
    searchStore.getErrorIsShow(true)
    Router.push(
      {
        path: '/pageError',
        query: {keyword: undefined},
      },
    )

  } else {
    emits('update:isShow', false)
    Router.push(
      {
        path: '/searchDetails',
        query: {keyword: value.value},
      },
    )
  }
  emits('update:isShow', false)
}
//清空历史搜索
const clearHistory = () => {
  historyList.value = []
  localStorage.removeItem('historyList')
}
// 点击取消
const emits = defineEmits(['update:isShow', 'update:valueDta'])
const cancelHandel = () => {
  searchStore.getErrorIsShow(true)
  searchData.value = []
  if (route.meta.walk) {
    Router.back()
  } else {
    emits('update:isShow', false)
  }
}

// 点击热门推荐
const historyItemHandel = (item: string) => {
  selectItem(item)
}
//点击历史搜索
const historyHandel = (item1: string, index1: number) => {
  const dataIndex = historyList.value.findIndex(item => {
    return item === item1
  })
  historyList.value = [historyList.value[dataIndex], ...historyList.value]
  selectItem(item1)
}
watch(historyList, (newValue) => {
}, {deep: true})

// 监视输入框失去焦点
const loseFocus = () => {

}
// 获取输入框实例
const inputRef = ref()
</script>

<style lang="less" scoped>
:deep(.van-search) {
  padding: 0;
}

:deep(.van-cell) {
  background-color: #f4f4f4;
}

.content {
  height: 100%;
  background-color: #f4f4f4;

  .main {
    background-color: #fff;
    padding: 15px 15px 0 15px;
    width: 100%;
    box-sizing: border-box;

    .title {
      font-size: 15px;
      height: 45px;
      line-height: 45px;

      .search {
        font-size: 15px;
        color: #999999;
        font-weight: 400;
      }
    }

    .choose {
      width: 100%;
      box-sizing: border-box;
      display: flex;
      flex-wrap: wrap;
      background-color: #fff;

      .chooseItem {
        height: 25px;
        padding: 0 7.5px;
        font-size: 12px;
        border-radius: 5px;
        text-align: center;
        line-height: 25px;
        margin: 0 16px 16px 0;
      }

      .active {
        border: 1px solid red;
      }
    }

    .listData {
      display: flex;
      flex-direction: column;

      .item {
        height: 45px;
        line-height: 45px;
        border-bottom: 1px solid #d9d9d9;
        display: flex;
        justify-content: space-between;
        background-color: #fff;
        width: 100%;

        .goods {
          font-size: 16px;
        }

        .van-icon-arrow {
          font-size: 16px;
        }
      }
    }

    .historySearch {
      .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      :deep(.van-icon-delete-o) {
        font-size: 18px;
      }

      .item {
        display: flex;
        flex-wrap: wrap;

        .historyItem {
          height: 25px;
          padding: 0 7.5px;
          font-size: 12px;
          border: 1px solid #999999;
          border-radius: 5px;
          text-align: center;
          line-height: 25px;
          margin: 0 16px 16px 0;
        }
      }

      .title {
        font-size: 15px;
        height: 45px;
        line-height: 45px;
      }


    }
  }
}
</style>
